<?php

namespace app\service;

use app\common\BaseService;
use app\model\House;
use app\model\ProductProcess as ProcessModel;
use think\facade\Db;

class ProcessService extends BaseService
{
  public static function getInstance(): ProcessService
  {
    return parent::getInstance();
  }

  public static function getModel(): ProcessModel
  {
    return ProcessModel::getInstance();
  }

  public static function getDataByCondition($conditions)
  {
    return self::getModel()->getDataByCondition($conditions);
  }

  /*
   * 连house_in house_out查询process信息
   */
  public static function getProcessJoinHouse($conditions = [], $order = ['p.process_time' => 'DESC', 'p.id' => 'DESC']) {
//    $conditions[] = ['p.status', 1,'='];
    $db = Db::name('product_process')
      ->alias('p');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $db = $db->where($field, $op, $value);
    }
    return $db
      ->order($order)
      ->select()
      ->toArray();
  }

  /*
   * 计算肉码实际成本
   */
  public static function processCount($material, $product, $isAdd = 0) {
    // 获取所有库存原料成本
    $house = HouseService::getInstance()->getHouseJoinGoods([['h.process', 0, '=']]);
    $houseList = array_column($house, null, 'goods_id');
    // 获取所有成品数据
    $goods = GoodsService::getInstance()->getDataByCondition([['process', 1, '='], ['status', 1, '=']]);
    $goodsList = array_column($goods, null, 'id');
    // 获取所有分类
    $categoryList = CategoryService::getInstance()->getCategoryByCondition([['base', 0, '=']]);
    $categoryList = array_column($categoryList, 'category_name', 'id');
    $materialList = [];
    // 原料总成本
    $totalMaterialCost = 0;
    foreach ($material as $mValue) {
      if (isset($houseList[$mValue['goods_id']])) {
        $detailP = $houseList[$mValue['goods_id']];
        $totalMaterialCost += $mValue['count'] * $detailP['price'];
        if ($isAdd) {
          $materialList[] = [
            'category_id' => $detailP['category_id'],
            'category' => $categoryList[$detailP['category_id']],
            'goods_id' => $detailP['goods_id'],
            'goods' => $detailP['name'],
            'count' => $mValue['count'],
            'cost' => $mValue['cost'],
            'conversion' => $detailP['conversion']
          ];
        }
      }
    }
    $productList = [];
    // 参考总成本
    $totalDefaultCost = 0;
    foreach ($product as $pValue) {
      if (isset($goodsList[$pValue['goods_id']])) {
        if (!floatval($goodsList[$pValue['goods_id']]['price_in'])) {
          return ['status' => false, 'msg' => '商品：'.$goodsList[$pValue['goods_id']]['name'].'，参考成本为空'];
        }
        $totalDefaultCost += $pValue['count'] * $goodsList[$pValue['goods_id']]['price_in'];
      } else {
        return ['status' => false, 'msg' => '商品不存在'];
      }
    }
//    if (!$totalDefaultCost) {
//      return ['status' => false, 'msg' => '参考总成本为0，请完善参考成本'];
//    }
    foreach ($product as $value) {
      if (isset($goodsList[$value['goods_id']])) {
        $detail = $goodsList[$value['goods_id']];
        // 实际成本 = ((参考成本 * 数量)/参考总成本 * 实际总成本) / 数量
        // 优化得：参考成本 / 参考总成本 * 实际总成本
        $cost = $totalDefaultCost ? round($detail['price_in'] / $totalDefaultCost * $totalMaterialCost, 2) : 0;
        $productList[] = [
          'category_id' => $detail['category_id'],
          'category' => $categoryList[$detail['category_id']],
          'goods_id' => $detail['id'],
          'goods' => $detail['name'],
          'unit_in' => $detail['unit_in'],
          'count' => $value['count'],
          'cost' => $cost,
          'total_cost' => round($cost * $value['count'], 2),
          'price_in' => $detail['price_in'],
          'total' => $detail['price_in'] * $value['count'],
          'conversion' => $detail['conversion'],
        ];
      }
    }
    if ($isAdd) {
      return ['status' => true, 'data' => ['house_in' => $productList, 'house_out' => $materialList]];
    } else {
      return ['status' => true, 'data' => $productList];
    }
  }

  /*
   * 获取加工明细
   */
  public static function getProcessDetail($processTime) {
    $materialList = [];
    $productList = [];
    // 获取process
    $process = self::getModel()
      ->where('process_time', 'like', date('Y-m-d', strtotime($processTime)).'%')
      ->find();
    $process = $process ? $process->toArray() : [];
    // 获取原料明细
    if ($process) {
      $material = HouseOutService::getInstance()->getHouseOutJoinGoods([['h.sell_number',$process['house_out_num'],'=']]);
      foreach ($material as $mValue) {
        $materialList[] = [
          'category_id' => $mValue['category_id'],
          'category' => $mValue['category_name'],
          'goods_id' => $mValue['goods_id'],
          'goods' => $mValue['name'],
          'cost' => $mValue['price'],
          'unit' => $mValue['unit'],
          'count' => $mValue['count'],
          'house_count' => $mValue['house_count'],
          'total' => round($mValue['count'] * $mValue['price'], 2),
        ];
      }
      // 获取成品明细
      $product = HouseInService::getInstance()->getHouseInJoinGoods([['o.house_in_number',$process['house_in_num'],'=']]);
      foreach ($product as $pValue) {
        $productList[] = [
          'category_id' => $pValue['category_id'],
          'category' => $pValue['category_name'],
          'goods_id' => $pValue['goods_id'],
          'goods' => $pValue['name'],
          'price_in' => $pValue['default_price'],
          'unit_in' => $pValue['unit_in'],
          'count' => $pValue['count_in'],
          'cost' => $pValue['price_in'],
          'total' => round($pValue['count_in'] * $pValue['default_price'], 2),
          'total_cost' => $pValue['total_amount']
        ];
      }
    }
    return ['materialList' => $materialList, 'productList' => $productList];
  }

  /*
   * 保存记录
   */
  public static function saveProcess($houseIn, $houseOut, $processTime) {
    // 判断时候含有此时数据
    $have = self::getInstance()->getProcessJoinHouse([['p.process_time', $processTime.'%', 'like']]);
    if ($have) {
      $have = $have[0];
      if ($have['status']) {
        return ['status' => false, 'msg' => '该数据已提交，不得修改'];
      }
      $houseInOrder = HouseInService::getModel()
        -> where('house_in_number', '=', $have['house_in_num'])
        ->find()
        ->toArray();
    }
    // 新增原料损耗数据
    $addHouseOut = [];
    // 获取损耗单号
    $houseOutList = HouseOutService::getInstance()->getHouseOutByCondition([['insert_time', $processTime.'%', 'like'], ['sell_number', 'JG%', 'LIKE']]);
    $arr1 = array_unique(array_column($houseOutList, 'sell_number'));
    $count1 = $have ? count($arr1) : count($arr1) + 1;
    $num1 = str_pad($count1, 4, '0',STR_PAD_LEFT);
    $houseOutNumber = 'JG'.date('Ymd', strtotime($processTime)).$num1;

    foreach ($houseOut as $out) {
      $addHouseOut[] = [
        'goods_id' => $out['goods_id'],
        'sell_number' => $houseOutNumber,
        'price' => $out['cost'],
        'count' => $out['count'],
        'sell_price' => $out['cost'],
        'base' => 0,
        'comment' => '加工',
        'type' => 1,
        'process' => 0,
        'status' => 0,
        'sale_time' => $processTime,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    // 新增成本数据
    $addHouseIn = [];
    // 获取入库单号
    $houseInList = HouseInService::getModel()
      ->where('insert_time', 'like', $processTime.'%')
      ->where('house_in_number', 'LIKE', 'JG%')
      ->select()
      ->toArray();
    $arr = array_unique(array_column($houseInList, 'house_in_number'));
    $count2 = $have ? count($arr) : count($arr) + 1;
    $num = str_pad($count2, 4, '0',STR_PAD_LEFT);
    $houseInNumber = 'JG'.date('Ymd', strtotime($processTime)).$num;

    $addHouseInOrder = [
      'house_in_number' => $houseInNumber,
      'process' => 1,
      'comment' => '生成肉码',
      'status' => 0,
      'default_time' => $processTime,
      'house_in_time' => date('Y-m-d'),
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    foreach ($houseIn as $in) {
      $totalAmount = round($in['cost'] * $in['count'], 2);
      $count = $in['count'] * $in['conversion'];
      $addHouseIn[] = [
        'goods_id' => $in['goods_id'],
        'in_order_id' => '',
        'price' => $count ? round($totalAmount / $count, 2) : 0,
        'count' => $count,
        'total_amount' => $totalAmount,
        'price_in' => $in['cost'],
        'count_in' => $in['count'],
        'comment' => '生成肉码',
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    // 新增数据到process表
    $insertProcess = [
      'house_out_num' => $houseOutNumber,
      'house_in_num' => $houseInNumber,
      'process_time' => $processTime,
      'status' => 0,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];

    self::getModel()->startTrans();
    try {
      // 删除house_in和house_out
      if ($have) {
        $res4 = self::getModel()
          ->where('id', '=', $have['id'])
          ->delete();
        if ($res4 === false) {
          throw new \Exception('删除process失败');
        }
        $res5 = HouseInService::getModel()
          ->where('house_in_number', '=', $have['house_in_num'])
          ->delete();
        if ($res5 === false) {
          throw new \Exception('删除house_in_order失败');
        }
        $res7 = HouseInService::getDetailModel()
          ->where('in_order_id', '=', $houseInOrder['id'])
          ->delete();
        if ($res7 === false) {
          throw new \Exception('删除house_in失败');
        }
        $res6 = HouseOutService::getModel()
          ->where('sell_number', '=', $have['house_out_num'])
          ->delete();
        if ($res6 === false) {
          throw new \Exception('删除house_out失败');
        }
      }
      // 新增house_out表
      if ($addHouseOut) {
        $res1 = HouseOutService::getModel()->insertAll($addHouseOut);
        if ($res1 === false) {
          throw new \Exception('新增house_out失败');
        }
      }
      // 新增house_in_order表
      if ($addHouseInOrder) {
        $res2 = HouseInService::getModel()
          ->insertGetId($addHouseInOrder);
        if ($res2 === false) {
          throw new \Exception('新增house_in_order失败');
        }
      }
      // 新增house_in表
      if ($addHouseIn) {
        foreach ($addHouseIn as &$v) {
          $v['in_order_id'] = $res2;
        }
        $res3 = HouseInService::getDetailModel()->insertAll($addHouseIn);
        if ($res3 === false) {
          throw new \Exception('新增house_in失败');
        }
      }
      // 新增product_process表
      if ($insertProcess) {
        $res4 = self::getModel()->save($insertProcess);
        if($res4 === false) {
          throw new \Exception('新增process失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
  * 提交保存
  */
  public static function handleProcess($houseIn, $houseOut, $processTime) {
    // 判断时候含有此时数据
    $process = self::getInstance()->getProcessJoinHouse([['p.process_time', $processTime.'%', 'like']]);
    if ($process) {
      $process = $process[0];
      if ($process['status']) {
        return ['status' => false, 'msg' => '该数据已提交'];
      }
    } else {
      return ['status' => false, 'msg' => '数据尚未保存'];
    }
    $houseOutList = HouseOutService::getInstance()->getHouseOutByCondition([['sell_number', $process['house_out_num'], '=']]);
    $houseInList = HouseInService::getInstance()->getHouseInJoinGoods([['o.house_in_number', $process['house_in_num'], '=']]);
    $houseOutList = array_column($houseOutList, null, 'goods_id');
    $houseInList = array_column($houseInList, null, 'goods_id');

    // 获取当前库存
    $house = HouseService::getInstance()->getHouseJoinGoods();
    $house = array_column($house, null, 'goods_id');
    // 更新house
    $updateHouse = [];
    // 新增成品库存
    $insertHouse = [];
    // 修改house_out
    $updateHouseOut = [];

    // 循环原料出库
    foreach ($houseOut as $oValue) {
      // === 判断是否保存 ====
      if (!isset($houseOutList[$oValue['goods_id']])) {
        return ['status' => false, 'msg' => '数据尚未保存'];
      }
      // 保存后的数据
      $material = $houseOutList[$oValue['goods_id']];
      if ($oValue['count'] != $material['count'] || $oValue['cost'] != $material['price']) {
        return ['status' => false, 'msg' => '数据尚未保存'];
      }
      $mHouse = $house[$material['goods_id']];
      // 判断数量是否不足
      if ($material['count'] > $mHouse['count']) {
        $msg = $mHouse['name'].'库存不足';
        return ['status' => false, 'msg' => $msg];
      }
      $updateHouse[] = [
        'id' => $mHouse['id'],
        'count' => round($mHouse['count'] - $material['count'], 2),
        'total_amount' => round(($mHouse['count'] - $material['count']) * $mHouse['price'], 2),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      $updateHouseOut[] = [
        'id' => $material['id'],
        'status' => 1,
        'sale_time' => $processTime,
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    // 循环成本入库
    foreach ($houseIn as $iValue) {
      // === 判断是否保存 ====
      if (!isset($houseInList[$iValue['goods_id']])) {
        return ['status' => false, 'msg' => '数据尚未保存'];
      }
      $product = $houseInList[$iValue['goods_id']];
      if ($iValue['count'] != $product['count_in'] || $iValue['cost'] != $product['price_in'] || $iValue['total_cost'] != $product['total_amount']) {
        return ['status' => false, 'msg' => '数据尚未保存'];
      }
      $pHouse = [];
      $totalAmount = 0;
      $price = 0;
      // 是否存在库存
      if (isset($house[$product['goods_id']])) {
        $pHouse = $house[$product['goods_id']];
        $totalAmount = round($pHouse['total_amount'] + $product['total_amount'], 2);
        $price = $pHouse['count'] + $product['count_in'] ? round(($pHouse['total_amount'] + $product['total_amount']) / ($pHouse['count'] + $product['count_in']), 2) : 0;
        $updateHouse[] = [
          'id' => $pHouse['id'],
          'count' => round($pHouse['count'] + $product['count_in'], 2),
          'price' => $price,
          'total_amount' => $totalAmount,
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      } else {
        $insertHouse[] = [
          'goods_id' => $product['goods_id'],
          'price' => $product['price_in'],
          'count' => $product['count_in'],
          'total_amount' => $product['total_amount'],
          'process' => $product['process'],
          'status' => 1,
          'insert_time' => date('Y-m-d H:i:s'),
          'last_update_time' => date('Y-m-d H:i:s'),
        ];
      }
    }

    self::getModel()->startTrans();
    try {
      // 更新house表
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->saveAll($updateHouse);
        if ($res1 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 新增house表
      if ($insertHouse) {
        $res2 = HouseService::getModel()
          ->saveAll($insertHouse);
        if ($res2 === false) {
          throw new \Exception('新增house失败');
        }
      }
      // 更新house_out表
      if ($updateHouseOut) {
        $res3 = HouseOutService::getModel()
          ->saveAll($updateHouseOut);
        if ($res3 === false) {
          throw new \Exception('更新house_out失败');
        }
      }
      // 更新house_in_order表
      $res4 = HouseInService::getModel()
        ->where('house_in_number', '=', $process['house_in_num'])
        ->save(['status' => 1, 'last_update_time' => date('Y-m-d H:i:s')]);
      if ($res4 === false) {
        throw new \Exception('更新house_in_order失败');
      }
      // 修改process
      $res5 = self::getModel()
        ->where('id', '=', $process['id'])
        ->save(['status' => 1, 'last_update_time' => date('Y-m-d H:i:s')]);
      if ($res5 === false) {
        throw new \Exception('更新process失败');
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
  * 删除某日后的数据
  */
  public static function deleteProcess($processTime) {
    $processList = self::getModel()
      ->where('process_time', '>=', $processTime)
      ->select()
      ->toArray();
    if (!$processList) {
      return ['status' => false, 'msg' => '该日期后无数据'];
    }
    // 获取house表实时数据
    $houseList = HouseService::getModel()
      ->select()
      ->toArray();
    $houseList = array_column($houseList, null, 'goods_id');

    // ===== 获取相关的原料与肉码 =====
    // 获取原料出库数据
    $materialAll = [];
    $outNum = array_unique(array_column($processList, 'house_out_num'));
    if ($outNum) {
      // 原料出库详情
      $materialList = HouseOutService::getModel()
        ->where('sell_number', 'IN', $outNum)
        ->where('status', '=', 1)
        ->select()
        ->toArray();
      $materialAll = array_unique(array_column($materialList, 'goods_id'));
    }
    // 获取肉码入库数据
    $productAll = [];
    $inNum = array_unique(array_column($processList, 'house_in_num'));
    if ($inNum) {
      // 肉码入库详情
      $productList = HouseInService::getInstance()->getHouseInJoinGoods([['o.house_in_number', $inNum, 'IN'], ['o.status', 0,'<>']]);
      $productAll = array_unique(array_column($productList, 'goods_id'));
    }
    // ===== 获取相关肉码store表实时数据 =====
    $storeList = StoreService::getModel()
      ->where('goods_id', 'IN', $productAll)
      ->select()
      ->toArray();
    // 获取门店实时数据
    $storeList2 = [];
    $new = [];
    foreach ($storeList as $s) {
      $str = $s['goods_id'].'-'.$s['base'];
      $storeList2[$str] = $s;
      $new[$s['id']] = $s;
    }
    $storeList = $new;
    $storeAll = array_column($storeList, 'id');

    // ===== 还原原料 (撤回总部原料领用出库)=====
    // 1. 更新原料库存 2. 删除原料出库数据($outNum)
    $updateHouse = [];
    if ($materialList) {
      foreach ($materialList as $material) {
        if (!isset($houseList[$material['goods_id']])) {
          return ['status' => false, 'msg' => '商品有误'];
        }
        $house = $houseList[$material['goods_id']];
        if (isset($updateHouse[$house['id']])) {
          $updateHouse[$house['id']]['count'] += $material['count'];
          $updateHouse[$house['id']]['total_amount'] += $material['price'] * $material['count'];
          $updateHouse[$house['id']]['price'] = round($updateHouse[$house['id']]['total_amount'] / $updateHouse[$house['id']]['count'], 2);
        } else {
          $updateHouse[$house['id']] = [
            'id' => $house['id'],
            'count' => $house['count'] + $material['count'],
            'total_amount' => $house['total_amount'] + ($material['price'] * $material['count']),
            'price' => round(($house['total_amount'] + $material['price'] * $material['count'])/($house['count'] + $material['count']), 2),
            'last_update_time' => date('Y-m-d H:i:s')
          ];
        }
      }
    }

    // =====  还原损耗 (撤回门店肉码损耗出库)=====
    // 1. 门店肉码增加 2. 删除相关肉码的损耗($delLossId)
    $updateStore = [];
    $lossList = StoreLossService::getModel()
      ->where('insert_time', '>=', $processTime)
      ->where('store_id', 'IN', $storeAll)
      ->where('status', '=', 1)
      ->select()
      ->toArray();
    $delLossId = array_column($lossList, 'id');
    if ($lossList) {
      foreach ($lossList as $loss) {
        $store = $storeList[$loss['store_id']];
        if (isset($updateStore[$store['id']])) {
          $updateStore[$store['id']]['count'] += $loss['count'];
          $updateStore[$store['id']]['total_amount'] += $loss['price_before'] * $loss['count'];
          $updateStore[$store['id']]['price'] = round($updateStore[$store['id']]['total_amount'] / $updateStore[$store['id']]['count'], 2);
        } else {
          $updateStore[$store['id']] = [
            'id' => $store['id'],
            'count' => $store['count'] + $loss['count'],
            'total_amount' => $store['total_amount'] + $loss['price_before'] * $loss['count'],
            'price' => round(($store['total_amount'] + $loss['price_before'] * $loss['count'])/($store['count'] + $loss['count']), 2),
            'last_update_time' => date('Y-m-d H:i:s')
          ];
        }
      }
    }

    // =====  还原肉码出库 (总部肉码出库)=====
    // 1. 仓库肉码增加 2. 门店肉码减少
    $updateHouseOutId = [];
    $updateInnerId = [];
    $updateOrderId = [];
    // 获取InnerPurchase
    $con1 = [
      ['i.goods_id',$productAll, 'IN'],
      ['o.status', 1, '='],
      ['o.confirm_time', $processTime, '>=']
    ];
    $innerList = InnerPurchaseService::getInstance()->getInnerJoinGoods($con1);
    $innerIds = array_unique(array_column($innerList, 'inner_order_id'));
    $orderNum = InnerPurchaseService::getInstance()->getConnectCount($innerIds);
    $orderNum = array_column($orderNum, 'num', 'id');
    foreach ($innerList as $i) {
      $updateInnerId[] = $i['id'];
      if (isset($orderNum[$i['inner_order_id']])) {
        $orderNum[$i['inner_order_id']] -= 1;
        if (!$orderNum[$i['inner_order_id']]) {
          $updateOrderId[] = $i['inner_order_id'];
        }
      }
    }
    // 获取HouseOut
    $con2 = [
      ['goods_id',$productAll, 'IN'],
      ['status', 1, '='],
      ['type', 2, '='],
      ['insert_time', $processTime, '>=']
    ];
    $houseOut = HouseOutService::getInstance()->getHouseOutByCondition($con2);
    $updateHouseOutId = array_column($houseOut, 'id');
    foreach ($houseOut as $value) {
      if (!isset($houseList[$value['goods_id']])) {
        return ['status' => false, 'msg' => '商品有误'];
      }
      // 修改house
      $houseData = $houseList[$value['goods_id']];
      if (isset($updateHouse[$houseData['id']])) {
        $updateHouse[$houseData['id']]['count'] += $value['count'];
        $updateHouse[$houseData['id']]['total_amount'] += $value['price'] * $value['count'];
        $updateHouse[$houseData['id']]['price'] = round($updateHouse[$houseData['id']]['total_amount'] / $updateHouse[$houseData['id']]['count'], 2);
      } else {
        $updateHouse[$houseData['id']] = [
          'id' => $houseData['id'],
          'count' => $houseData['count'] + $value['count'],
          'total_amount' => $houseData['total_amount'] + ($value['price'] * $value['count']),
          'price' => round(($houseData['total_amount'] + $value['price'] * $value['count'])/($houseData['count'] + $value['count']), 2),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
      // 修改store
      $str = $value['goods_id'].'-'.$value['base'];
      if (!isset($storeList2[$str])) {
        return ['status' => false, 'msg' => '商品有误'];
      }
      $storeData = $storeList2[$str];
      if (isset($updateStore[$storeData['id']])) {
        $updateStore[$storeData['id']]['count'] = strval($updateStore[$storeData['id']]['count']) - strval($value['count']);
        $updateStore[$storeData['id']]['total_amount'] = strval($updateStore[$storeData['id']]['total_amount']) - strval($value['sell_price'] * $value['count']);
        $updateStore[$storeData['id']]['price'] = $updateStore[$storeData['id']]['count'] ? round($updateStore[$storeData['id']]['total_amount'] / $updateStore[$storeData['id']]['count'], 2) : 0;
      } else {
        $updateStore[$storeData['id']] = [
          'id' => $storeData['id'],
          'count' => strval($storeData['count']) - strval($value['count']),
          'total_amount' => strval($storeData['total_amount']) - strval($value['sell_price'] * $value['count']),
          'price' => strval($storeData['count']) - strval($value['count']) ? round(($storeData['total_amount'] - $value['sell_price'] * $value['count'])/($storeData['count'] - $value['count']), 2) : 0,
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
    }

    // ===== 还原肉码生产入库 (总部肉码入库) ======
    // 1. 仓库肉码减少
    foreach ($productList as $value2) {
      if (!isset($houseList[$value2['goods_id']])) {
        return ['status' => false, 'msg' => '商品有误'];
      }
      // 修改house
      $houseData2 = $houseList[$value2['goods_id']];
      if (isset($updateHouse[$houseData2['id']])) {
        $updateHouse[$houseData2['id']]['count'] = strval($updateHouse[$houseData2['id']]['count']) - strval($value2['count']);
        $updateHouse[$houseData2['id']]['total_amount'] = $updateHouse[$houseData2['id']]['count'] ? strval($updateHouse[$houseData2['id']]['total_amount']) - strval($value2['price'] * $value2['count']) : 0;
        $updateHouse[$houseData2['id']]['price'] = $updateHouse[$houseData2['id']]['count'] ? round($updateHouse[$houseData2['id']]['total_amount'] / $updateHouse[$houseData2['id']]['count'], 2) : 0;
      } else {
        $updateHouse[$houseData2['id']] = [
          'id' => $houseData2['id'],
          'count' => strval($houseData2['count']) - strval($value2['count']),
          'total_amount' => strval($houseData2['count']) - strval($value2['count']) ? strval($houseData2['total_amount']) - strval($value2['total_amount']) : 0,
          'price' => strval($houseData2['count']) - strval($value2['count']) ? round(($houseData2['total_amount'] - $value2['price'] * $value2['count'])/($houseData2['count'] - $value2['count']), 2) : 0,
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
    }
    $change = [
      'status' => 0,
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    self::getModel()->startTrans();
    try {
      // 修改process（删除）
      if ($processList) {
        $res1 = self::getModel()
          ->where('id', 'IN', array_column($processList, 'id'))
          ->delete();
        if ($res1 === false) {
          throw new \Exception('更新process失败');
        }
      }
      // 修改houseOut（删除）
      if ($outNum) {
        $res2 = HouseOutService::getModel()
          ->where('sell_number', 'IN', $outNum)
          ->save($change);
        if ($res2 === false) {
          throw new \Exception('更新house_out失败');
        }
      }
      // 修改store_loss（删除）
      if ($delLossId) {
        $res3 = StoreLossService::getModel()
          ->where('id', 'IN', $delLossId)
          ->save($change);
        if ($res3 === false) {
          throw new \Exception('更新store_loss失败');
        }
      }
      // 修改house_out（删除）
      if ($updateHouseOutId) {
        $res4 = HouseOutService::getModel()
          ->where('id', 'IN', $updateHouseOutId)
          ->save($change);
        if ($res4 === false) {
          throw new \Exception('更新house_out失败');
        }
      }
      // 修改inner_purchase_order（删除）
      if ($updateOrderId) {
        $res5 = InnerPurchaseService::getModel()
          ->where('id', 'IN', $updateOrderId)
          ->save($change);
        if ($res5 === false) {
          throw new \Exception('更新inner_purchase_order失败');
        }
      }
      // 修改inner_purchase（删除）
      if ($updateInnerId) {
        $res6 = InnerPurchaseService::getDetailModel()
          ->where('id', 'IN', $updateInnerId)
          ->save($change);
        if ($res6 === false) {
          throw new \Exception('更新inner_purchase失败');
        }
      }
      // 修改house_in_order（删除）
      if ($inNum) {
        $res7 = HouseInService::getModel()
          ->where('house_in_number', 'IN', $inNum)
          ->save($change);
        if ($res7 === false) {
          throw new \Exception('更新house_in_order失败');
        }
      }
      // 修改house_in（删除）
      if ($productList) {
        $res8 = HouseInService::getDetailModel()
          ->where('id', 'IN', array_column($productList, 'id'))
          ->save($change);
        if ($res8 === false) {
          throw new \Exception('更新house_in失败');
        }
      }
      // 修改仓库
      if ($updateHouse) {
        $res9 = HouseService::getModel()
          ->saveAll($updateHouse);
        if ($res9 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 修改门店仓库
      if ($updateStore) {
        $res10 = StoreService::getModel()
          ->saveAll($updateStore);
        if ($res10 === false) {
          throw new \Exception('更新store失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }


}